import { _decorator, Camera, Component, find, instantiate, Node, Prefab, UITransform, Vec3, Widget } from 'cc';
import ResManager from '../common/ResManager';
import { PrefabEnum } from '../common/PrefabEnum';
const { ccclass, property } = _decorator;

@ccclass('GuideController')
export class GuideController extends Component {
    @property(Node)
    mask:Node
    @property(Node)
    bg:Node

   
    stepList:string[] = []
    step:number = 0

    /**
     * 创建一个新手引导
     * @returns 
     */
    static async create(): Promise<GuideController> {
        let prefab = await ResManager.instance.loadAssetByUrl<Prefab>(PrefabEnum.Guide)
    
        let node = instantiate(prefab)

        find('Canvas').addChild(node)

        return node.getComponent(GuideController)
    }

    /**
     * 设置遮罩的位置
     * @param pos 世界坐标
     */
    setMaskPosition(pos:Vec3){
        this.mask.position = pos
        let widget = this.bg.getComponent(Widget)
        widget.left = 0
        widget.right = 0
        widget.top = 0
        widget.bottom = 0
    }

    /**
     * 设置新手引导的路径
     * @param stepList 节点的路径列表 string[]
     */
    setStepList(stepList:string[]){
        this.stepList = stepList
       
        this.nextStep()

    }

   
    /**
     * 下一步
     * @returns 
     */
    async nextStep(){
        if(this.step >= this.stepList.length){
            this.node.destroy()
            return
        }

        let node = await this.findNode(this.stepList[this.step])
        if(!node){
            this.node.destroy()
            return
        }

        if(!node.active){
            this.node.destroy()
            return
        }

        node.on(Node.EventType.TOUCH_END, this.nextStep, this)

        let camera = find('Canvas/UICamera').getComponent(Camera)

        let pos = camera.convertToUINode(node.worldPosition, this.node)
        this.setMaskPosition(pos)
        let transform = node.getComponent(UITransform)
        let width = transform.width 
        let height = transform.height
        transform = this.mask.getComponent(UITransform)
        transform.width = width + 40
        transform.height = height + 40
        this.step ++
    }

    /**
     * 查找节点，如果没找到，就等待0.5s再次查找，共找10次
     *  @param s 节点的路径
     */
    async findNode(s:string):Promise<Node>{
        let node 
        for(let i = 0; i< 10; i++){
           
            node = find(s)
            if(node){
                break
            } else{
                await new Promise((resolve) => {
                    this.scheduleOnce(() => {
                        resolve(1)
                    }, 0.2)
                })
            }
        }

        return node
    }
}


